package com.bang.study.query;

import org.elasticsearch.action.get.GetRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.transport.TransportClient;
import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.common.text.Text;
import org.elasticsearch.common.transport.InetSocketTransportAddress;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightField;
import org.elasticsearch.search.suggest.Suggest;
import org.elasticsearch.search.suggest.SuggestBuilder;
import org.elasticsearch.search.suggest.SuggestBuilders;
import org.elasticsearch.search.suggest.completion.CompletionSuggestionBuilder;
import org.elasticsearch.transport.client.PreBuiltTransportClient;

import java.net.InetAddress;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

/**
 * @ClassName: GrandParentChildQuery
 * @author: BANG
 * @Date: 2020/01/16 15:08
 * @Version: 1.0
 * @Modified By:
 * @Desc: TODO
 *
 *GET /news_website/news/_search
 * {
 *   "suggest": {
 *     "my-suggest" : {
 *       "prefix" : "大话西游",
 *       "completion" : {
 *         "field" : "title.suggest"
 *       }
 *     }
 *   }
 * }
 */
public class CompletionSuggestQuery {

    public static void main(String[] args) throws Exception{
        Settings settings = Settings.builder()
                .put("cluster.name", "elasticsearch")
                .put("client.transport.sniff", true)
                .build();
        TransportClient client = new PreBuiltTransportClient(settings).addTransportAddress(
                new InetSocketTransportAddress(InetAddress.getByName("localhost"), 9300)
        );

        //field的名字,前缀(输入的text),以及大小size
        CompletionSuggestionBuilder suggestionBuilderDistrict = SuggestBuilders.completionSuggestion("title.suggest")
                .prefix("大话西游");
        SuggestBuilder suggestBuilder = new SuggestBuilder();
        suggestBuilder.addSuggestion("my-suggest", suggestionBuilderDistrict);//添加suggest

        SearchResponse searchResponse = client.prepareSearch("news_website").setTypes("news")
                .suggest(suggestBuilder)
                .get();
        Suggest suggest = searchResponse.getSuggest();
        List<? extends Suggest.Suggestion.Entry<? extends Suggest.Suggestion.Entry.Option>> entries = suggest.getSuggestion("my-suggest").getEntries();
        for (Suggest.Suggestion.Entry<? extends Suggest.Suggestion.Entry.Option> entry : entries) {
            List<? extends Suggest.Suggestion.Entry.Option> options = entry.getOptions();
            for (Suggest.Suggestion.Entry.Option option : options) {
                String s = option.getText().toString();
                System.err.println(s);
            }
        }


        client.close();

    }
}
